var api = require('../../utils/api.js');
var app = getApp();
Page({
  onShareTimeline:function(){
    return {
      title:"智克艺术 - 音乐播放器 - "+this.data.nowMusic.name,
      query:{id:this.data.actId,musicId:this.data.musicId},
      imageUrl:this.data.nowMusic.cover||this.data.nowMusic.url
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    isIn: 0,
    keywords: '',
    idx: '',
    audioWay: 0, //播放方式 0顺序播放 1随机播放 2单曲循环
    playState: 1, //播放状态
    nowmiao: 0, //当前时间
    allmiao: 100, //全部时间
    nowMusic: [],
    audioList: [],
    nowMinSec:'0:00',
    allMinSec:'0:00',
    waiting:true,
    Times:""
  },
  getClickTimes(){
   let Times =  String(this.data.nowMusic.click);
   if(Times.length>4){
    Times =  (Number(Times)/10000).toFixed(1) + "w"
   }else if(Times.length>3){
    Times =  (Number(Times)/1000).toFixed(1) + "k"
   }
   this.setData({
    Times
   })
  },
  audioInit1() {
    const that = this
    var bgAudioMannager= wx.getBackgroundAudioManager();
      // console.log('正在播放第'+(that.data.idx+1)+'首歌曲')
      // var nowMusic = that.data.audioList[that.data.idx];
    console.log('audioInit1执行')
    var nowMusic = that.data.nowMusic
    wx.setStorageSync('nowMusic', nowMusic)
    that.setData({
      nowMusic
    })
    // for(var index in 5){
    //   if(that.data.audioList==''){
    //     that.getMusicList(that.data.musicId,'', pageindex,0)
    //   }
    // }
    // bgAudioMannager.title = that.data.audioList[that.data.idx].name;
    // bgAudioMannager.singer = that.data.audioList[that.data.idx].singer;
    // bgAudioMannager.coverImgUrl = that.data.audioList[that.data.idx].cover;
    // bgAudioMannager.src = that.data.audioList[that.data.idx].src;
    bgAudioMannager.title = that.data.nowMusic.name;
    bgAudioMannager.coverImgUrl = that.data.nowMusic.cover;
    bgAudioMannager.src = that.data.nowMusic.url;
    setTimeout(()=>{
      that.nonitor()
    },1000)
  },
  pauseMusic() {
    if (this.data.playState == 1) {
      //暂停
      wx.getBackgroundAudioManager().pause()
    } else {
      //播放
      if (wx.getBackgroundAudioManager().src == undefined) {
        this.audioInit1()
      }
      wx.getBackgroundAudioManager().play()
    }
  },
  // 返回
  back(){
    wx.navigateTo({
      url: '/pages/musicDetail/musicDetail?musicId='+this.data.musicId,
    })
  },
  playMusic(idx) {
    console.log('playMusic执行')
    // console.log('playMusic拿到的idx'+idx)
    // var nowMusic = this.data.audioList[this.data.idx] || wx.getStorageSync('nowMusic');
    var nowMusic = this.data.nowMusic || wx.getStorageSync('nowMusic')
    wx.setStorageSync('nowMusic', nowMusic)
    this.setData({
      nowMusic
    })
    this.setData({
      playState: 1
    })
    this.audioInit1();
  },
  //拖动快进
  sliderChange(e) {
    this.setData({
      nowmiao: e.detail.value
    })
    wx.getBackgroundAudioManager().seek(this.data.nowmiao)
  },
  playFunc() {
    this.setData({
      playState: 1
    })
  },
  pauseFunc() {
    this.setData({
      playState: 0
    })
  },
  //下一曲
  nextPlay() {
    const that = this
    that.setData({
      waiting:true
    })
    wx.request({
      url:app.globalData.host+'/Music/music_one',
      data:{
        id:that.data.nowMusic.id,
        type:that.data.audioWay,
        option:2,
        token:wx.getStorageSync('token')
      },
      method:'POST',
      success(res){
        console.log(res.data.data.name)
        let arr = res.data.data
        that.setData({
          nowMusic:arr,
          waiting:false
        })
        that.playMusic()
      },
      fail(err){
        console.log(err)
      }
    })
    return
    if (this.data.audioList.length == 0) {
      wx.showToast({
        title: '请求失败!请返回后刷新再试试,如持续出现该问题请联系技术服务人员',
        icon:'none'
      })
      return
    }
    if (this.data.audioWay == 1|| this.data.audioWay == 2) {
      //随机
      console.log('随机播放', this.data.audioList.length)
      this.setData({
        idx: Math.floor(Math.random() * Math.round(this.data.audioList.length)) % this.data.audioList.length
      })
    } else if (this.data.audioWay == 0) {
      //顺序
      console.log('顺序播放')
      if (this.data.idx >= (this.data.audioList.length - 1)) {
        this.setData({
          idx: 0
        })
      } else {
        this.setData({
          idx: parseInt(this.data.idx)+1
        })
      }
    } //单曲循环
    this.audioInit1();
  },
  //上一曲
  upPlay() {
    const that = this
    that.setData({
      waiting:true
    })
    wx.request({
      url:app.globalData.host+'/Music/music_one',
      data:{
        id:that.data.nowMusic.id,
        type:that.data.audioWay,
        option:1,
        token:wx.getStorageSync('token')
      },
      method:'POST',
      success(res){
        console.log(res.data.data.name)
        let arr = res.data.data
        that.setData({
          nowMusic:arr,
          waiting:false
        })
        that.playMusic()
      },
      fail(err){
        console.log(err)
      }
    })
    return
    if(this.data.idx==0&&this.data.pageindex!==0){
      this.getMusicList(this.data.musicId,'', this.data.pageindex,this.data.pageindex-1);
    }
    if (this.data.audioList.length == 0) {
      wx.showToast({
        title: '请求失败!请返回后刷新再试试,如持续出现该问题请联系技术服务人员',
        icon:'none'
      })
      return
    }
    if (this.data.audioWay == 1||this.data.audioWay == 2) {
      //随机
      console.log('随机');
      this.setData({
        idx: Math.floor(Math.random() * 10) % this.data.audioList.length
      })
    } else if (this.data.audioWay == 0) {
      //顺序
      console.log('顺序')
      if (this.data.idx < 1) {
        this.setData({
          idx: this.data.audioList.length - 1
        })
      } else {
        this.setData({
          idx: parseInt(this.data.idx) - 1
        })
      }
    } //单曲循环
  //  wx.setStorageSync('nowMusic', this.data.audioList[this.data.idx])
    this.audioInit1()
  },
  //切换模式
  checkPlay(e) {
    console.log(e)
    if (this.data.audioWay > 1) {
      this.setData({
        audioWay: 0
      })
    } else {
      this.setData({
        audioWay: this.data.audioWay + 1
      })
    }
    
  },
  //监听音乐状态
  nonitor(){
    let bgAudioMannager = wx.getBackgroundAudioManager();
    // 开始播放
    bgAudioMannager.onPlay(() => {
      console.log('播放')
      this.playFunc()
    })
    // 暂停播放
    bgAudioMannager.onPause(() => {
      console.log('暂停')
      this.pauseFunc()
    })
    // 当前音乐播放完毕
    bgAudioMannager.onEnded(() => {
      this.nextPlay()
    })
    // 监听音乐加载中事件
    bgAudioMannager.onWaiting(()=>{
      this.setData({
        waiting:true
      })
    })
    // 监听音乐播放进度
    bgAudioMannager.onTimeUpdate(() => {
       // 转成分/秒格式
     let allMinSec= Math.floor(bgAudioMannager.duration/60)+':'+ parseInt(bgAudioMannager.duration%60)
     let nowMinSec= Math.floor(bgAudioMannager.currentTime/60)+':'+ parseInt(bgAudioMannager.currentTime%60)
     if(parseInt(bgAudioMannager.currentTime%60)<10){
      nowMinSec= Math.floor(bgAudioMannager.currentTime/60)+':0'+ parseInt(bgAudioMannager.currentTime%60)
     }
     if(parseInt(bgAudioMannager.duration%60)<10){
      allMinSec= Math.floor(bgAudioMannager.duration/60)+':0'+ parseInt(bgAudioMannager.duration%60)
     }
    //
     if(parseInt(bgAudioMannager.currentTime%60)>0){
       this.setData({
         waiting:false
       })
     }
      this.setData({
        nowmiao: Math.floor(bgAudioMannager.currentTime),
        allmiao: Math.floor(bgAudioMannager.duration),
        nowMinSec,
        allMinSec
      })
     
    })
  },
  //获取歌曲列表
  getMusicList(musicId, search, page) {
    console.log('页面第一个请求开始')
    const that = this
    // console.log('getMusicList拿到的page'+page)
    var nowMusic = that.data.audioList[that.data.idx] || wx.getStorageSync('nowMusic');
    //nowMusic = [{ ...nowMusic }]
    wx.setStorageSync('nowMusic', nowMusic)
    that.setData({
      nowMusic
    })
    api.fetchApi('music/music_list', {
      page,
      id: musicId,
      search,
      token: wx.getStorageSync('token') || ''
    }).then(res => {
      console.log('页面第一个请求结束')
      var count = res.count;
      var audioList = that.data.audioList,
        audioList1 = res.music_list;
      if (audioList1.length == 0 && page > 1) {
        return
      }
      page == 1 ? audioList = res.music_list : audioList = [...audioList, ...audioList1]
      console.log(page,audioList)
      // audioList = [...audioList, ...audioList1]
      if (audioList.length == 0) {
        console.log(nowMusic)
        that.setData({
          nowMusic
        })
        // return
      }
      that.setData({
        audioList,
        page,
        count,
      })
    //  var itemIndex = this.data.audioList.findIndex((item)=>item.id==wx.getStorageSync('nowMusic').id)
    //   if (wx.getStorageSync('nowMusic').music_class_id==this.data.musicId){
    //     this.setData({
    //       isIn:1
    //     })
    //   }
    //   console.log('itemIndex '+itemIndex)
    //   itemIndex < 0 ? itemIndex='':''
    //   this.setData({
    //     idx: itemIndex
    //   })
    //  if (isSearch == 1){
    //   this.audioInit1();
    //   }
    })
  },
  // 首次进入播放
  initPlay(id){
    const that = this
    that.setData({
      waiting:true
    })
    wx.request({
      url:app.globalData.host+'/Music/music_one',
      data:{
        id,
        type:that.data.audioWay,
        option:0,
        token:wx.getStorageSync('token')
      },
      method:'POST',
      success(res){
        if(res.data.code!==2000){
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }
        console.log(res.data.data.name)
        let arr = res.data.data
        that.setData({
          nowMusic:arr,
          waiting:false
        })
        that.getClickTimes();
        that.playMusic();
      },
      fail(err){
        console.log(err)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    const that = this
    that.setData({
      musicId:options.musicId
    })
    that.initPlay(options.id)
    // that.getMusicList(options.musicId,'', pageindex,0);
    let item = wx.getStorageSync('nowMusic');
    let bgAudioMannager = wx.getBackgroundAudioManager();
    if (bgAudioMannager.src == wx.getStorageSync('nowMusic').src){
      that.nonitor();
    }else{
      //说明在播放收藏的歌曲 
      if (bgAudioMannager.src == wx.getStorageSync('nowMusic1').src){
        wx.setStorageSync('nowMusic', '')
      }
      if (wx.getStorageSync('nowMusic') && !wx.getStorageSync('nowMusic1')) {
        bgAudioMannager.title = item.name;
        bgAudioMannager.singer = item.singer;
        bgAudioMannager.coverImgUrl = item.cover;
        bgAudioMannager.src = item.src;
        that.nonitor();
      }
    }
    that.playMusic(options.idx)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log('页面卸载')
    app.globalData.playState=this.data.playState;
    this.nonitor();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})